package com.youlu.campus.service.data.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.interactive.vo.ActivitySignUpRequest;
import com.youlu.campus.entity.UniversityInfo;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.VO.req.LogFileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.Scanner;

@Slf4j
@Service
public class LogFileDataVerifyService {


    @Autowired
    private MongoTemplate mongoTemplate;

    public static void main(String[] args) throws IOException {
        LogFileVO logFile = new LogFileVO();
        logFile.setFileName("nohup.out");
        logFile.setLogfilePath("/Users/liuyun/Desktop");
        logFile.setLogFilterKeyword("com.youlu.campus.service.activity.impl.ActivityServiceImpl - :>>> 用户参加活动");
        logFile.setKeyword("608115fdff341566a58ec3d9");
       // checkLogFile(logFile);

    }

    public  void checkLogFile(LogFileVO logFile) throws FileNotFoundException {
        String fileName = logFile.getFileName();
        String logfilePath = logFile.getLogfilePath();
        String logFilterKeyword = logFile.getLogFilterKeyword();
        String keyword = logFile.getKeyword();
        File file = new File(logfilePath+File.separator+fileName);
        if(!file.exists()){
            throw new BusinessException(fileName+"不存在");
        }
        log.info(" 开始解析文件 - >{}",logfilePath+fileName);
        FileInputStream fileInput = null;
        Scanner scanner = null;
        fileInput = new FileInputStream(file);
        try {
            scanner = new Scanner(fileInput, "UTF-8");
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                boolean matches = line.matches(".*(" + logFilterKeyword + ").*");
                if (!matches) {
                    continue;
                }
                if (!line.matches(".*(" + logFile.getKeyword() + ").*")) {
                    continue;
                }
                String logJson = line.substring(line.indexOf("{"), line.lastIndexOf("}") + 1);
                log.error("输出行 - >{}", logJson);
                try {
                    ActivitySignUpRequest activitySignUpRequest = JSON.parseObject(logJson, ActivitySignUpRequest.class);
                    String userId = activitySignUpRequest.getUserId();
                    Query query = new Query();
                    query.addCriteria(Criteria.where("userId").is(userId));
                    query.addCriteria(Criteria.where("activityId").is(keyword));
                    query.addCriteria(Criteria.where("joined").is(Boolean.TRUE));
                    boolean exists = this.mongoTemplate.exists(query, UserParticipateActivityInfo.class);
                    if (exists) {
                        log.error(" exists activityId - >{} userId - > {}", keyword, userId);
                        continue;
                    }
                    UserParticipateActivityInfo userParticipateActivityInfo = new UserParticipateActivityInfo();
                    BeanUtils.copyProperties(activitySignUpRequest, userParticipateActivityInfo);
                    userParticipateActivityInfo.setSignUpTime(new Date());
                    userParticipateActivityInfo.setJoined(Boolean.TRUE);
                    userParticipateActivityInfo.setCreatedTime(new Date());
                    userParticipateActivityInfo.setQaScore(70D);
                    UniversityInfo universityInfo = this.mongoTemplate.findById(activitySignUpRequest.getUniversityId(), UniversityInfo.class);
                    if (Objects.nonNull(universityInfo)) {
                        userParticipateActivityInfo.setUniversityName(universityInfo.getName());
                    }
                    userParticipateActivityInfo.setPassed(Boolean.TRUE);
                    userParticipateActivityInfo.setLogSource(Boolean.TRUE);
                    this.mongoTemplate.save(userParticipateActivityInfo);
                } catch (Exception e) {
                    log.error("错误", e);
                    continue;

                }
            }
        }catch (Exception e){
            log.error("错误", e);

        }finally {
            if(Objects.nonNull(fileInput)){
                try {
                    fileInput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(Objects.nonNull(scanner)){
                scanner.close();
            }
        }
        log.info("结束解析文件 - >{}",logfilePath+fileName);

//        FileChannel fileChannel = null;
//        try {
//            RandomAccessFile raf = new RandomAccessFile(file, "r");
//             fileChannel = raf.getChannel();
//            ByteBuffer buffer = ByteBuffer.allocate(1000);
//            while (true) {
//                // clear方法重设缓冲区，使它可以接受读入的数据
//                buffer.clear();
//                // 从输入通道中将数据读到缓冲区
//                int r = fileChannel.read(buffer);
//                if (r == -1) {
//                    break;
//                }
//                // flip方法让缓冲区可以将新读入的数据写入另一个通道
//                buffer.flip();
//                byte[] bytes = buffer.array();
//                String charW = new String(bytes);
//                if(charW.length()>=logFilterKeyword.length()&&charW.contains(logFilterKeyword)){
//                    System.out.println("输出行数:"+charW);
//                }
//            }
//            raf.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }finally {
//            if(Objects.nonNull(fileChannel)){
//                try {
//                    fileChannel.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }


    }
}
